package com.elink.enginerring.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.ws.rs.DefaultValue;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.elink.enginerring.co.BaseCo;
import com.elink.enginerring.co.ThesisCo;
import com.elink.enginerring.common.Constant;
import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.domain.Thesis;
import com.elink.enginerring.service.ThesisService;
import com.elink.enginerring.util.JSONUtil;

@Api(value = "论文接口")
@RestController
@RequestMapping(value = "/api/thesis")
public class ThesisController {
	@Autowired
	private ThesisService thesisService;

	/**
	 * 获取论文列表
	 * @param co
	 * @return
	 */
	@RequestMapping(value = "/getList", method = RequestMethod.GET)
	@ApiOperation(value = "论文列表")
	public Map<String, Object> getList(@ModelAttribute @Valid ThesisCo co) {
		return thesisService.getFilesList(co);
	}
	
	/**
	 * 统计个人中心-首页--工程论文库
	 * @return
	 */
	@RequestMapping(value = "/getThesisList", method = RequestMethod.GET)
	@ApiOperation(value = "统计个人中心-首页--工程论文库",httpMethod="GET",notes="统计个人中心-首页--工程论文库")
	public Map<String, Object>getThesisList(@ApiParam(value="二级分类id",required=true)@RequestParam(value="scId") int scId){
		return thesisService.getThesisList(scId);
	}
	
	/**
	 * 获取论文精选
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getThesisBest",method = RequestMethod.GET)
	@ApiOperation(value = "项目首页--论文精选", notes="项目首页--获取论文精选")
	public Map<String, Object>getThesisBest(@ApiParam(value="获取论文精选,默认为5条",required=false,defaultValue="5")
	@RequestParam(value = "count",required=false,defaultValue="5")int count){
		return thesisService.getThesisBest(count);
	}
	
	/**
	 * 添加论文
	 * @param thesis
	 * @return
	 */
	@RequestMapping(value="/add",method = RequestMethod.POST)
	@ApiOperation(value = "添加论文")
	public Map<String, Object>add(@ModelAttribute @Valid Thesis thesis,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>)request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		thesis.setUserId(userId);
		return thesisService.add(thesis);
	}
	
	/**
	 * 	修改文件 	
	 * @param file
	 * @param dcIds
	 * @return
	 */
	@RequestMapping(value="/update",method = RequestMethod.POST)
	@ApiOperation(value = "修改论文")
	public Map<String, Object>update(@ModelAttribute @Valid Thesis thesis,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>)request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return thesisService.update(thesis,userId);
	}
	
	
	/**
	 * 论文详情
	 * @param thesisId
	 * @return
	 */
	@RequestMapping(value="/get",method = RequestMethod.GET)
	@ApiOperation(value = "论文详情")
	public Map<String, Object>get(
			@ApiParam(value="论文id",required=true)@RequestParam(value = "thesisId",required=true)String thesisId,HttpServletRequest request){
		String userId =null;
		try {
			@SuppressWarnings("unchecked")
			Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
			userId =  userInfo.get("userId").toString();
		} catch (Exception e) {
		}
		return thesisService.getInfo(thesisId,userId);
	}
	
	/**
	 * 获取共享论文
	 * @param thesisId
	 * @return
	 */
	@RequestMapping(value="/getShare",method = RequestMethod.GET)
	@ApiOperation(value = " 获取共享论文")
	public Map<String, Object>getShare(
			@ApiParam(value="论文id",required=true)@RequestParam(value = "thesisId",required=true)String thesisId,HttpServletRequest request){
		String userId =null;
		try {
			@SuppressWarnings("unchecked")
			Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
			userId =  userInfo.get("userId").toString();
		} catch (Exception e) {
		}
		return thesisService.getShare(thesisId,userId);
	}
	/**
	 * 获取下载排行
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getDownLoadRank",method = RequestMethod.GET)
	@ApiOperation(value = "下载排行")
	public Map<String, Object>getDownLoadRank(
			@ApiParam(value="显示条数,默认为10条",defaultValue="10") @RequestParam("count") @DefaultValue("10")int count){
		return thesisService.getDownLoadRank(count);
	}
	
	
	/**
	 * 获取相关推荐
	 * @param thesisId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getRelevant",method = RequestMethod.GET)
	@ApiOperation(value = "相关推荐")
	public Map<String, Object>getRelevant(
			@ApiParam(value="资料id",required=true)@RequestParam("thesisId")String thesisId,
			@ApiParam(value="显示条数",required=true,defaultValue="6")
			@RequestParam(value = "count",required=true,defaultValue="6")int count){
		return thesisService.getRelevant(thesisId,count);
	}
	
	/**
	 * 猜你喜欢
	 * @param thesisId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getLike",method = RequestMethod.GET)
	@ApiOperation(value = "猜你喜欢")
	public Map<String, Object>getLike(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "thesisId",required=true)String thesisId,
			@ApiParam(value="显示条数,默认为6条",required=true,defaultValue="6")
			@RequestParam(value = "count",required=true,defaultValue="6")int count){
		return thesisService.getLike(thesisId,count);
	}
	
	/**
	 * 获取热搜词
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getKeyWord",method = RequestMethod.GET)
	@ApiOperation(value = "获取热搜词")
	public Map<String, Object>getKeyWord(
			@ApiParam(value="显示条数,默认为6条",required=false,defaultValue="6")
			@RequestParam(value = "count",required=false,defaultValue="6")int count){
		return thesisService.getKeyWord(count);
	}
	
	/**
	 * 获取论文分类
	 * @param thesisId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getRelevantType",method = RequestMethod.GET)
	@ApiOperation(value = "获取论文分类",httpMethod="GET",notes="获取相关论文分类")
	public Map<String, Object>getRelevantType(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "thesisId",required=true)String thesisId,
			@ApiParam(value="获取相关论文分类,默认为9条",required=false,defaultValue="9")
			@RequestParam(value = "count",required=false,defaultValue="9")int count){
		return thesisService.getRelevantType(thesisId,count);
	}
	
	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
	@ApiOperation(value = "上传文件")
	public Map<String, Object> uploadFile(
			@ApiParam(value="上传文件",required=true)
			@RequestParam("file") MultipartFile file) {		
		
		String fileName = file.getOriginalFilename();
		String suffix = "";
		String newFileName = "";
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			suffix = fileName.substring(index);
		}
		if(!isExcept(suffix)){
			return JSONUtil.getJSON(ErrorType.FILE_TYPE_ERROR);
		}
		Date d = new Date();
		int year = d.getYear()+1900;
		int month = d.getMonth()+1;
		int day = d.getDate();
		
		String basePath = year+month+day +"/"+d.getTime();
	     newFileName = "file/" +basePath + suffix;
		 String path = Constant.WEB_SERVER_PATH+"/" + newFileName;
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new java.io.File(path));
			String url =Constant.WEB_SERVER_URL+"/" + newFileName;//下载路径
			//预览路径
//			String previewName = basePath+ ".pdf";
//			
//			String previewPath = Constant.WEB_SERVER_PATH+"/" + "pdf/"+ previewName;
//			OpenOffice2PDF office2pdf = new OpenOffice2PDF();
//			
//			office2pdf.openOffice2Pdf(path,previewName);
//			FileUtils.copyFile(new java.io.File(previewName), new java.io.File(previewPath));
//			
//			String previewUrl = Constant.WEB_SERVER_URL+"/" + "pdf/"+ previewName ;//预览路径
//			
//	        Map<String, Object> map = new HashMap<String, Object>();
//	        map.put("downloadUrl", url);
//	        map.put("previewUrl", previewUrl);
	        
			return JSONUtil.getJSON(ErrorType.SUCCESS, url);

		} catch (IOException e) {
			return JSONUtil.getJSON(ErrorType.HANDLE_FILE_ERROR);
		}
	}
	
	/**
	 * 下载文件
	 * @param thesisId
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@ApiOperation(value = "下载文件")
	public Map<String, Object> downloadFile(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "thesisId",required=true)String thesisId,
			HttpServletResponse response,HttpServletRequest request
			) throws Exception {
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return  thesisService.download(response,request,userId,thesisId);
	}
	
	/**
	 * 分页获取我上传的论文
	 * @param co
	 * @return
	 */
	@RequestMapping(value="/myUpload",method = RequestMethod.GET)
	@ApiOperation(value="分页获取我上传的论文")
	public Map<String, Object> myUploadFile(@ModelAttribute @Valid BaseCo co, @ApiParam(value="搜索关键词",required=false,defaultValue="")
	@RequestParam(value="keyWord",required=false,defaultValue="")String keyWord,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return thesisService.getUploadByUserId(co,userId,keyWord);
	}
	
	/**
	 * 分页获取TA上传的论文
	 * @param co
	 * @param keyWord
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/uploadByUserId",method = RequestMethod.GET)
	@ApiOperation(value="分页获取TA上传的论文",httpMethod="GET",notes="分页获取TA上传的论文")
	public Map<String, Object> uploadByUserId(
			@ModelAttribute @Valid BaseCo co,@ApiParam(value="搜索关键词",required=false,defaultValue="")
			@RequestParam(value="keyWord",required=false,defaultValue="")String keyWord,@ApiParam(value="用户ID",required=true)
			@RequestParam(value="userId",required=true)String userId){
		return thesisService.getUploadByUserId(co,userId,keyWord);
	}
	/**
	 * 分页获取我下载的论文
	 * @param co
	 * @return
	 */
	@RequestMapping(value="/myDownLoad",method = RequestMethod.GET)
	@ApiOperation(value="分页获取我下载的论文")
	public Map<String, Object> myDownLoadFile(@ModelAttribute @Valid BaseCo co, @ApiParam(value="搜索关键词",required=false,defaultValue="")
	@RequestParam(value="keyWord",required=false,defaultValue="")String keyWord,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return thesisService.getDownLoadByUserId(co,userId,keyWord);
	}
	
	/**
	 * 校验文件的格式
	 * @param url
	 * @return
	 */
	public 	boolean isExcept(String url){
		String[] excepts={".docx",".doc",".ppt",".xls"};
		boolean flag=false;
		for(String e:excepts){
			if(url!=null&&url.endsWith(e)){
				flag=true;
				break;
			}
		}
		return flag;
	}
}
